﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CollegeShop.Infrastructure.Entities.Entity;
using CollegeShop.Infrastructure.Entities.Enum;
using CollegeShop.Infrastructure.Entities;
using CollegeShop.Tool.Framework;
using CollegeShop.Infrastructure.Entities.Repository;

namespace CollegeShop.Biz
{
    public class UserBiz
    {
        /// <summary>
        /// 用户注册
        /// 如果成功返回String.Empty
        /// 如果失败返回失败原因
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="nickname"></param>
        /// <returns></returns>
        public static string Register(string username, string password, string nickname)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                return "输入有误";
            }
            if (new User().Any(c => c.UserName == username))
            {
                return "该用户名已经存在，请重新输入";
            }
            var user = new User()
            {
                UserName = username,
                Password = AesAlgorithm.Encrypt(password),
                IsActivate = true,
                IsRefuse = false,
                RealName = nickname,
                NickName = nickname,
                SystemRole = (SystemRole)SystemRole.User,
                CreateDate = DateTime.Now,
                Email = string.Empty
            }.PostAdd();
            if (user == null)
            {
                return "注册失败，请稍后重试";
            }
            return string.Empty;
        }
        public static int LocalLogin(string code, ClientType clientType)
        {
            if (!String.IsNullOrEmpty(code))
            {
                if (!new Anonymous().Any(c => c.ClientCode == code && c.ClientType == (int)clientType))
                {
                    if (new Anonymous()
                    {
                        ClientCode = code,
                        ClientType = clientType,
                        OnlineTime = DateTime.Now
                    }.PostAdd() == null)
                    {
                        return 0;
                    }
                }
                System.Web.Security.FormsAuthentication.SetAuthCookie(code, true);
                return 1;           
            }
            return 0;
        }

        public static Dictionary<int,List<User>> GetStaffGroup()
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.User
                            where c.SystemRole != (int)SystemRole.User
                            group c by c.SystemRole into g
                            select g)
                           .ToList()
                           .Select(c =>
                               new KeyValuePair<int, List<User>>(c.Key, c.Select(u => new User().Set(u)).ToList()))
                           .ToDictionary(
                            c => c.Key,
                            c => c.Value);
                var staff = (from c in ctx.User
                             join _u in ctx.Salesunit 
                             on c.UserName equals _u.LinkMan into ug
                             from u in ug.DefaultIfEmpty()
                             where c.SystemRole == (int)SystemRole.Staff || c.SystemRole == (int)SystemRole.Director
                             select new { c, u })
                            .ToList();
                if (list.Keys.Contains((int)SystemRole.Staff))
                {
                    var stafflist = list[(int)SystemRole.Staff];
                    foreach (var item in stafflist)
                    {
                        var user = staff.FirstOrDefault(c=>c.c.UserName == item.UserName);
                        if(user != null)
                        {
                            if (user.u != null)
                            {
                                item.SalesUnit = new Salesunit().Set(user.u);
                            }
                        }
                    }
                }
                return list;

            }
        }

        public static List<User> GetStaffs()
        {
            return new User().FindAll(c => c.SystemRole == (int)SystemRole.Staff);
        }


        /// <summary>
        /// true:不存在 false:存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool UserNotExists(string userName)
        {
            if (!String.IsNullOrEmpty(userName))
            {
                using (Context ctx = new Context())
                {
                    return !ctx.User.Any(c => c.UserName == userName);
                }
            }
            return false;
        }

        public static List<Deliveryaddress> LoadDeliveryAddresses(string code)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Deliveryaddress
                            join s in ctx.Salesunit
                             on c.SalesUnitID equals s.ID
                            where c.UserName == code
                            select new { c, s })
                           .ToList()
                           .Select(c => new Deliveryaddress().Set(c.c).LoadSaleUnit(c.s))
                           .ToList();
                return data;
            }
        }
        /// <summary>
        /// 取消所有默认配送地址设置
        /// </summary>
        /// <param name="p"></param>
        public static void UpdateDeliveryAddressNoDefault(string username)
        {
            using (Context ctx = new Context())
            {
                ctx.Update<T_Deliveryaddress>()
                    .Set(c => c.isDefault, false)
                    .WhereSet(c => c.UserName, WhereOperator.Equal, username)
                    .End().Excute();
            }
        }
        /// <summary>
        /// 检查收货地址
        /// </summary>
        /// <param name="username"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        public static Deliveryaddress CheckDeliveryAddresses(string username, int address)
        {
            return new Deliveryaddress().Find(c => c.UserName == username && c.ID == address);
        }

        /// <summary>
        /// 查询Staff信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static User GetStaffInfo(string userName)
        {
            if (!String.IsNullOrEmpty(userName))
            {
                var user = new User().Find(userName);
                if (user != null && (user.SystemRole == SystemRole.Director || user.SystemRole == SystemRole.Staff) && user.SalesUnitID > 0)
                {
                    using (Context ctx = new Context())
                    {
                        var data = (from c in ctx.User
                                    join u in ctx.Salesunit
                                      on c.SalesUnitID equals u.ID
                                    select new { c, u })
                                  .FirstOrDefault();
                        if (data != null)
                        {
                            return new User().Set(data.c).LoadSaleUnit(data.u);
                        }

                    }
                }
            }
            return null;
        }
    }
}
